package question5.com.qee.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Jdbc2UserDaoImpl implements UserDao {
    @Override
    public int add(User user) {
        TransactionJdbcSession transactionJdbcSession = new TransactionJdbcSession();
        try {
            Map<String, Object> paramMap = MapUtils.toMap(user.getClass(), user);

            return transactionJdbcSession.insert("insert into tb_user(id,name,feature,create_time,update_time) values(?,?,?,?,?)", paramMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int remove(Long id) {
        TransactionJdbcSession transactionJdbcSession = new TransactionJdbcSession();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", id);
            return transactionJdbcSession.update("delete from tb_user where id=?", paramMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int update(User user) {
        TransactionJdbcSession transactionJdbcSession = new TransactionJdbcSession();
        try {
            Map<String, Object> paramMap = MapUtils.toMap(user.getClass(), user);
            return transactionJdbcSession.update("update tb_user set name=?, feature=?, update_time=?  where id=?", paramMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<User> getAll() {
        TransactionJdbcSession transactionJdbcSession = new TransactionJdbcSession();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            return transactionJdbcSession.selectList("select * from tb_user", paramMap, User.class);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
